package com.ray.woodencreate.mq;

import com.ray.woodencreate.logs.SystemLogBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author bo shen
 * @Description: 消息分发器
 * @Class: MessageDispatch
 * @Package com.toptoday.woodencreate.mq
 * @date 2018/11/27 9:03
 * @company <p></p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class MessageDispatch {

    private RocketConsumerConfig config;

    public MessageDispatch(RocketConsumerConfig config) {
        this.config = config;
    }

    /**
     * 处理消息分配方法
     * @param messageExt
     * @return
     */
    public boolean dispatch(MessageExt messageExt){
        String topic = messageExt.getTopic();
        log.info(new SystemLogBuilder().appendLevelTips().appendMsg(String.format("接收消息=>TOPIC:%s,MESSAGEID:%s",topic,messageExt.getMsgId())).bulidString());
        List<Consumer> customers = config.getCustomers(topic);
        if(ObjectUtils.isEmpty(customers)){
            return true;
        }
        if(customers.size() == 1){
            return customers.get(0).sendMessage(messageExt).getData();
        }
        for(Consumer customer : customers){
            customer.sendMessage(messageExt).getData();
        }
        return true;
    }
}
